package sfs

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/api_messages"
	"github.com/chicken-team-outside/chicken_transmission/driver"
	"github.com/golang/protobuf/proto"
	"go.uber.org/zap"
)

func (p *FsClient) Truncate(ctx context.Context, clientId uint64, path string, size int64) error {
	r, err := p.sendRequest(ctx, clientId, api_messages.MessageType_Truncate, &api_messages.TruncateQuery{Path: path, Size: size})
	if err == nil {
		err = decodeStatusMessage(r)
	}
	return err
}

func (p *FsClient) TruncateProvider(ctx context.Context, header *api_messages.MessageHeader, data []byte) {
	if ctx.Err() == nil {
		query := new(api_messages.TruncateQuery)
		err := proto.Unmarshal(data, query)
		var client driver.LocalDriver
		if err == nil {
			client = p.GetLocal()
			if client == nil {
				err = ErrNotSetLocalDriver
			}
		}
		err = client.Truncate(query.Path, query.Size)
		err = p.sendReplyByHeader(ctx, header, encodeStatusMessage(err))
		if err != nil {
			zap.L().Error("send reply error", zap.Error(err), zap.Any("header", header), zap.Any("query", query))
		}
	}
}
